__author__ = 'chenglin'
# -*- coding: utf-8 -*-
import uuid

from flask import Module, flash, request, g, current_app, \
    abort, redirect, url_for, session, jsonify

from flask_babel import gettext as _
from flask_principal import identity_changed, Identity, AnonymousIdentity
from app.models.users import User
from app.forms import  LoginForm
from  flask import render_template
from app.extensions import db


account = Module(__name__)


@account.route("/login/", methods=("GET", "POST"))
def login():
    form = LoginForm(login=request.args.get("login", None),
                     next=request.args.get("next", None))

    # TBD: ensure "next" field is passed properly

    if form.validate_on_submit():
        user, authenticated = \
            User.query.authenticate(form.login.data,
                                    form.password.data)

        if user and authenticated:
            session.permanent = form.remember.data

            identity_changed.send(current_app._get_current_object(),
                                  identity=Identity(user.id))

            # check if openid has been passed in
            openid = session.pop('openid', None)
            if openid:
                user.openid = openid
                db.session.commit()

                flash(_("Your OpenID has been attached to your account. "
                      "You can now sign in with your OpenID."), "success")


            else:
                flash(_("Welcome back, %(name)s", name=user.username), "success")

            next_url = form.next.data

            if not next_url or next_url == request.path:
                next_url = url_for('user.posts', username=user.username)

            return redirect(next_url)

        else:

            flash(_("Sorry, invalid login"), "error")

    # return render_template("main.html")
    return render_template('account/index.html',
                           title=u'IM管理平台登录')

@account.route("/logout/")
def logout():

    flash(_("You are now logged out"), "success")
    identity_changed.send(current_app._get_current_object(),
                          identity=AnonymousIdentity())

    return redirect(url_for('frontend.index'))


@account.route("/forgotpass/", methods=("GET", "POST"))
def forgot_password():
    form = "11"
    # form = RecoverPasswordForm()

    if form.validate_on_submit():

        user = User.query.filter_by(email=form.email.data).first()

        if user:
            flash(_("Please see your email for instructions on "
                  "how to access your account"), "success")

            user.activation_key = str(uuid.uuid4())
            db.session.commit()

            body = render_template("emails/recover_password.html",
                                   user=user)

            # message = Message(subject=_("Recover your password"),
            #                   body=body,
            #                   recipients=[user.email])
            #
            # mail.send(message)

            return redirect(url_for("frontend.index"))

        else:

            flash(_("Sorry, no user found for that email address"), "error")

    return render_template("account/recover_password.html", form=form)


@account.route("/changepass/", methods=("GET", "POST"))
def change_password():

    user = None

    if g.user:
        user = g.user

    elif 'activation_key' in request.values:
        user = User.query.filter_by(
            activation_key=request.values['activation_key']).first()

    if user is None:
        abort(403)


    # form = ChangePasswordForm(activation_key=user.activation_key)
    form = ""

    if form.validate_on_submit():

        user.password = form.password.data
        user.activation_key = None

        db.session.commit()

        flash(_("Your password has been changed, "
                "please log in again"), "success")

        return redirect(url_for("account.login"))

    return render_template("account/change_password.html", form=form)




